<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="任务基本信息" name="first">
          <el-form
            ref="jobDefineFormRef"
            :model="form"
            label-width="120px"
            :rules="rules"
          >
            <el-row>
              <!-- 任务名称 -->
              <el-col :span="12">
                <el-form-item
                  :label="$t('jobDefine.jobCnName')"
                  prop="jobCnName"
                >
                  <el-input
                    v-model="form.jobCnName"
                    :placeholder="$t('jobDefine.jobNameRequired')"
                    maxlength="45"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
              </el-col>
              <!-- 任务分类 -->
              <el-col :span="12">
                <el-form-item :label="$t('jobDefine.classify')" prop="classify">
                  <jmash-select
                    v-model="form.classify"
                    :data="Dict.jobClassifyDict.values"
                    :placeholder="$t('jobDefine.classifyRequired')"
                    maxlength="45"
                    show-word-limit
                    filterable
                    allow-create
                    default-first-option
                  />
                </el-form-item>
              </el-col>
              <!-- 运行权重 -->
              <el-col :span="12">
                <el-form-item :label="$t('jobDefine.weight')" prop="weight">
                  <el-input-number
                    v-model="form.weight"
                    :placeholder="$t('jobDefine.weightRequired')"
                    :step="1"
                    :min="0"
                    clearable
                    class="maxVendors"
                  />
                </el-form-item>
              </el-col>
              <!-- 触发事件 -->
              <el-col :span="12">
                <el-form-item
                  :label="$t('jobDefine.eventName')"
                  prop="eventName"
                >
                  <el-input
                    v-model="form.eventName"
                    :placeholder="$t('jobDefine.eventNameRequired')"
                    maxlength="45"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
              </el-col>
              <!-- 触发事件内容 -->
              <el-col :span="24">
                <el-form-item
                  :label="$t('jobDefine.eventBody')"
                  prop="eventBody"
                >
                  <el-input
                    type="textarea"
                    v-model="form.eventBody"
                    :placeholder="$t('jobDefine.eventBodyRequired')"
                    :autosize="{ minRows: 4 }"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="formatJson"
                    >格式化JSON</el-button
                  >
                  <span style="color: #f00; font-size: 13px">{{
                    formattedJson
                  }}</span>
                </el-form-item>
              </el-col>
              <!-- 任务描述 -->
              <el-col :span="24">
                <el-form-item
                  :label="$t('jobDefine.jobDescribe')"
                  prop="jobDescribe"
                >
                  <el-input
                    v-model="form.jobDescribe"
                    type="textarea"
                    :autosize="{ minRows: 4 }"
                    maxlength="200"
                    show-word-limit
                    :placeholder="$t('jobDefine.jobDescribeRequired')"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="submitForm">
                {{ $t("common.save") }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="定时触发器" name="second" v-if="routerKey">
          <el-card shadow="never" class="table-container">
            <!-- 按钮开始 -->
            <template #header>
              <el-row>
                <el-col :span="17">
                  <!-- 新增 -->
                  <el-button
                    v-hasPerm="['jobs:job_trigger:add']"
                    type="primary"
                    @click="handleAdd"
                  >
                    {{ $t("common.add") }}
                  </el-button>
                </el-col>
                <el-col :span="7" class="container-float">
                  <!-- 固定列表 -->
                  <jmash-column-select
                    v-model="tableLabel"
                    label-name="jobs/job-trigger"
                  />
                </el-col>
              </el-row>
            </template>
            <!-- 按钮结束 -->
            <!-- 表格开始 -->
            <jmash-table
              ref="multipleTableRef"
              class="table-top"
              row-key="triggerId"
              :list-loading="listLoading"
              :data="jobTriggerData"
              :table-label="tableLabel"
              @selection-change="tableSelected"
              @sort-change="handleSort"
            >
              <!-- 开始时间 -->
              <template #startDate="scope">
                <span>
                  {{
                    proxy.$moment.formatDate(
                      scope.data.row.startDate,
                      "YYYY-MM-DD HH:mm:ss",
                    )
                  }}
                </span>
              </template>
              <!-- 是否立即开始 -->
              <template #startNow="scope">
                <span>
                  {{ Dict.jobTriggerDict.getValue(scope.data.row.startNow) }}
                </span>
              </template>
              <!-- 是否自定义 -->
              <template #isCustom="scope">
                <span>
                  {{ Dict.jobTriggerDict.getValue(scope.data.row.isCustom) }}
                </span>
              </template>

              <template #operation="scope">
                <!-- 编辑 -->
                <span
                  v-hasPerm="['jobs:job_trigger:update']"
                  class="el-button-color"
                  @click="handleEdit(scope.data.row)"
                >
                  {{ $t("common.edit") }}
                </span>
                <!-- 删除 -->
                <span
                  v-hasPerm="['jobs:job_trigger:delete']"
                  class="el-button-color dropdown-left"
                  @click="deleteRecord(scope.data.row)"
                >
                  {{ $t("common.delete") }}
                </span>
              </template>
            </jmash-table>
          </el-card>
          <!-- 新增编辑组件 -->
          <job-trigger-edit
            v-if="editDialog.visible"
            v-model="editDialog.visible"
            :title="editDialog.title"
            :job-key="routerKey"
            :trigger-key="triggerKey"
            @refresh="refreshTrigger"
            width="700px"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { useRoute } from "vue-router";
import {
  useTableHooks,
  type DialogRef,
  type TableColumn,
  type TableSort,
} from "jmash-core";
const route = useRoute();
import { ref, reactive, type Ref, getCurrentInstance } from "vue";
import {
  type FormInstance,
  type FormRules,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { proxy } = getCurrentInstance() as any;
import type {
  JobDefineFormReq,
  JobDefineCreateReq,
  JobDefineUpdateReq,
} from "@/api/jobs/job-define/types";
import { jobDefineApi } from "@/api/jobs/job-define/index";
import type {
  JobTriggerKey,
  JobTriggerModel,
  JobTriggerReq,
} from "@/api/jobs/job-trigger/types";
import { jobTriggerApi } from "@/api/jobs/job-trigger";
import jobTriggerEdit from "./jobTriggerEdit.vue";
import { Dict } from "@/api/jobs/index";
//任务分类
Dict.jobClassifyDict.useValues();
const queryParams = ref<JobTriggerReq>({});
const { tableHooks, multipleTableRef, listLoading } = useTableHooks(
  t,
  jobTriggerApi,
  queryParams,
);
const activeName = ref<string>("first");
const jobDefineFormRef = ref<FormInstance>();
const formattedJson = ref("");
const jobTriggerData = ref<Array<JobTriggerModel>>([]);
const emits = defineEmits(["refresh"]);
// 获取路由参数
const routerKey = ref<string>("");
routerKey.value = route.query.entityKey as string;
// 切换tab事件
function handleClick(tab: any) {
  activeName.value = tab.props.name;
  if (activeName.value === "second") {
    // 调用定时触发器列表数据
    jobTriggerWork();
  } else {
    // 解决接口返回客户端重复发起请求
    form.requestId = Math.random() * 10 + "";
  }
}
//任务定义新增开始
//格式化json
const formatJson = () => {
  try {
    const parsedJson = JSON.parse(form.eventBody as string);
    form.eventBody = JSON.stringify(parsedJson, null, 2);
    formattedJson.value = "";
  } catch (error) {
    formattedJson.value = "无效的JSON格式";
  }
};

// 表单数据
let form: JobDefineFormReq = reactive<JobDefineFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask: "jobCnName,weight,eventName,eventBody,jobDescribe",
  enable: true,
});
// 表单校验规则
const rules = reactive<FormRules<JobDefineFormReq>>({
  jobCnName: [
    {
      required: true,
      message: t("jobDefine.jobNameRequired"),
      trigger: "blur",
    },
  ],
  classify: [
    {
      required: true,
      message: t("jobDefine.classifyRequired"),
      trigger: "change",
    },
  ],
  weight: [
    {
      required: true,
      message: t("jobDefine.weightRequired"),
      trigger: "change",
    },
  ],
  eventName: [
    {
      required: true,
      message: t("jobDefine.eventNameRequired"),
      trigger: "blur",
    },
  ],
  eventBody: [
    {
      required: true,
      message: t("jobDefine.eventBodyRequired"),
      trigger: "change",
    },
  ],
});
//路由参数
if (route.query.entityKey) {
  jobDefineApi
    .findById({ jobName: route.query.entityKey as string })
    .then(({ data }) => {
      form = Object.assign(form, data);
    });
}
// 提交表单校验
const submitForm = async () => {
  await jobDefineFormRef.value?.validate((valid) => {
    if (valid) {
      //切换tab给定时任务主键ID赋值
      form.jobName = routerKey.value;
      if ((form as JobDefineUpdateReq).jobName) {
        jobDefineApi.update(form as JobDefineUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            // 跳转至定时触发器tab栏
            activeName.value = "second";
            // 刷新定时触发器列表
            jobTriggerWork();
          }
        });
      } else {
        jobDefineApi.create(form as JobDefineCreateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            // 根据任务主键ID 判断定时触发器tab栏是否显示
            routerKey.value = response.data.jobName as string;
            // 跳转至定时触发器tab栏
            activeName.value = "second";
            // 刷新定时触发器列表
            jobTriggerWork();
          }
        });
      }
    }
  });
};
//任务定义新增结束

//定时触发器列表开始
// 表格头部标题
let tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "jobTrigger.startDate",
    prop: "startDate",
    width: "160",
    isColumn: true,
    slotName: "startDate",
    columnType: "slot",
  },
  {
    label: "jobTrigger.startNow",
    prop: "startNow",
    width: "110",
    isColumn: true,
    slotName: "startNow",
    columnType: "slot",
  },
  {
    label: "jobTrigger.cron",
    prop: "cron",
    width: "200",
    isColumn: true,
  },
  {
    label: "jobTrigger.cronName",
    prop: "cronName",
    isColumn: true,
  },
  {
    label: "jobTrigger.isCustom",
    prop: "isCustom",
    width: "100",
    isColumn: true,
    slotName: "isCustom",
    columnType: "slot",
  },
  {
    label: "common.operate",
    width: "200",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);
//编辑Dialog
const editDialog = ref({
  title: t("common.edit"),
  visible: false,
} as DialogRef);
let triggerKey = reactive<JobTriggerKey>({});

// 定时器新增
function handleAdd() {
  triggerKey = reactive<JobTriggerKey>({});
  editDialog.value.title = t("common.add");
  editDialog.value.visible = true;
}

// 定时器编辑
function handleEdit(row: JobTriggerModel) {
  triggerKey.triggerId = row.triggerId as string;
  editDialog.value.title = t("common.edit");
  editDialog.value.visible = true;
}
//定时器删除
function deleteRecord(id: any) {
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.delete"), {
    cancelButtonText: t("common.cancel"),
    confirmButtonText: t("common.confirm"),
    type: "warning",
  })
    .then(() => {
      jobTriggerApi.delete(id).then((response: any) => {
        if (response.status === 200) {
          ElMessage({
            message: t("common.deleteSuccess"),
            type: "success",
          });
          jobTriggerWork();
        }
      });
    })
    .catch(() => {});
}
// 定时器列表
function jobTriggerWork() {
  jobTriggerApi.findList({ jobName: routerKey.value }).then(({ data }) => {
    jobTriggerData.value = data.results;
  });
}

/**
 * 从定时器子组件传过来的事件，刷新列表
 *
 * @returns {void}
 */
function refreshTrigger(value: boolean) {
  if (value) {
    jobTriggerWork();
  }
}
// 定时器行选择
function tableSelected(value: JobTriggerModel[]) {
  tableHooks.selectionRows.value = value;
}
// 定时器处理排序
function handleSort(sort: TableSort) {
  tableHooks.handleSort(sort.prop, sort.order);
}
//定时触发器列表结束
</script>
<style scoped lang="scss">
.maxVendors {
  width: 100%;
}
</style>
